<template>
  <view class="online-service-container">
    <!-- 头部导航 -->
    <!-- <CustomHeader 
      title="在线客服"
      back-text="返回"
      @back="goBack"
      @more="showMoreOptions"
      @moreOptions="showHistory"
      :showMoreOptions="'历史记录'"
      :showMore="false"
    /> -->
    <view class="header" @click="showHistory" style="display: flex; justify-content: end; padding: 10rpx 30rpx;">历史记录</view>
    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 问题类型 -->
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text class="label-text">问题类型</text>
        </view>
          <view class="form-input" @click="showProblemTypePicker">
           <text class="placeholder-text" v-if="!selectedProblemType">请选择问题类型</text>
           <text class="selected-text" v-else>{{ selectedProblemType }}</text>
           <u-icon name="arrow-right" size="24" color="#999"></u-icon>
         </view>
      </view>

      <!-- 问题描述 -->
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text class="label-text">问题描述</text>
        </view>
        <view class="form-textarea">
          <textarea 
            v-model="problemDescription" 
            placeholder="请详细描述你的问题和意见，我们会尽快为您处理..."
            class="textarea-input"
            :maxlength="500"
            show-confirm-bar="false"
            auto-height
          ></textarea>
          <view class="textarea-counter">
            <text class="counter-text" :class="{ 'warning': problemDescription.length > 450 }">
              {{ problemDescription.length }}/500
            </text>
          </view>
        </view>
      </view>

      <!-- 图片上传 -->
      <view class="form-item">
        <view class="form-label">
          <text class="required"></text>
          <text class="label-text">问题截图 (最多3张)</text>
        </view>
        <view class="image-upload-container">
          <view 
            class="image-item" 
            v-for="(image, index) in uploadedImages" 
            :key="index"
          >
            <image :src="image" class="uploaded-image" mode="aspectFill" @click="previewImage(index)"></image>
            <view class="delete-btn" @click="deleteImage(index)">
              <u-icon name="close" size="12" color="#fff"></u-icon>
            </view>
          </view>
          <view 
            class="upload-btn" 
            @click="chooseImage" 
            v-if="uploadedImages.length < 3"
          >
            <u-icon name="plus" size="24" color="#999"></u-icon>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
        <view class="upload-tip">
          <text class="tip-text">建议上传清晰的截图，有助于我们更快解决问题</text>
        </view>
      </view>

    </view>

    <!-- 提交按钮 -->
    <view class="submit-container">
      <u-button 
        type="primary" 
        :disabled="!canSubmit"
        @click="submitForm"
        :loading="isSubmitting"
        class="submit-btn"
      >
        {{ isSubmitting ? '提交中...' : '提交' }}
      </u-button>
    </view>

    <!-- 问题类型选择器 -->
    <u-picker 
      :show="showPicker" 
      :columns="[problemTypes]" 
      @confirm="onProblemTypeConfirm"
      @cancel="showPicker = false"
      :loading="false"
    ></u-picker>

    <!-- 更多选项弹窗 -->
    <u-popup :show="showMorePopup" @close="showMorePopup = false" mode="bottom">
      <view class="more-popup">
        <view class="popup-item" @click="clearForm">
          <u-icon name="reload" size="20" color="#666"></u-icon>
          <text class="popup-text">清空表单</text>
        </view>
        <view class="popup-item" @click="contactService">
          <u-icon name="phone" size="20" color="#666"></u-icon>
          <text class="popup-text">电话客服</text>
        </view>
        <view class="popup-cancel" @click="showMorePopup = false">
          <text class="cancel-text">取消</text>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import CustomHeader from '@/components/CustomHeader.vue'
import config from '@/config'
export default {
  name: 'OnlineService',
  components: {
    CustomHeader
  },
  data() {
    return {
      selectedProblemType: '',
      selectedProblemTypeId: '', // 新增：保存选中的问题类型ID
      problemDescription: '',
      uploadedImages: [],
      showPicker: false,
      showMorePopup: false,
      isSubmitting: false,
      problemTypes: [],
      problemTypesData: [], // 新增：保存原始数据
      imageUrls: []
    }
  },
  computed: {
    canSubmit() {
      return this.selectedProblemType && 
             this.problemDescription.trim()
    }
  },
  onLoad() {
    this.getProblemTypes()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    showHistory() {
      uni.navigateTo({
        url: '/pages/personalCenter/onlineService/history'
      })
    },
    async getProblemTypes() {
      try {
        const res = await this.$http.get('/h5/user/feedback/getFeedbackType')
        this.problemTypesData = res.data || []
        this.problemTypes = this.problemTypesData.map(item => item.name) || []
      } catch (error) {}
    },
    showProblemTypePicker() {
      this.showPicker = true
    },
    
    onProblemTypeConfirm(e) {
      const selectedName = e.value[0]
      this.selectedProblemType = selectedName
      const selectedItem = this.problemTypesData.find(item => item.name === selectedName)
      this.selectedProblemTypeId = selectedItem ? selectedItem.id : ''
      this.showPicker = false
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 3 - this.uploadedImages.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 检查图片大小
          const maxSize = 2 * 1024 * 1024 // 2MB
          const validImages = res.tempFilePaths.filter((path, index) => {
            // 检查文件大小
            const file = res.tempFiles[index]
            if (file && file.size > maxSize) {
              uni.showToast({
                title: '图片大小不能超过2MB',
                icon: 'none'
              })
              return false
            }
            return true
          })
          
          if (validImages.length !== res.tempFilePaths.length) {
            uni.showToast({
              title: '部分图片过大，已跳过',
              icon: 'none'
            })
          }
          
          this.uploadedImages = [...this.uploadedImages, ...validImages]
          res.tempFiles.forEach(item => {
            this.uploadImage(item)
          })
        },
        fail: (err) => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    async uploadImage(item) {
      const formData = new FormData()
      formData.append('file', item)
      try {
        const res = await fetch(config.baseUrl + '/h5/common/upload', {
          method: 'POST',
          body: formData,
          headers: {
            Authorization: 'Bearer ' + uni.getStorageSync('token')
          }
        });
        const { data } = await res.json();
        this.imageUrls.push(data.file)

      } catch (error) {
      }
    },
    
    deleteImage(index) {
      this.uploadedImages.splice(index, 1)
    },
    
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.uploadedImages
      })
    },
    
    showMoreOptions() {
      this.showMorePopup = true
    },
    
    clearForm() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有已填写的内容吗？',
        success: (res) => {
          if (res.confirm) {
            this.selectedProblemType = ''
            this.selectedProblemTypeId = ''
            this.problemDescription = ''
            this.uploadedImages = []
            this.imageUrls = []
            uni.showToast({
              title: '已清空',
              icon: 'success'
            })
          }
        }
      })
      this.showMorePopup = false
    },
    
    contactService() {
      uni.showModal({
        title: '联系客服',
        content: '客服电话：400-123-4567\n工作时间：9:00-18:00',
        showCancel: false,
        confirmText: '拨打'
      })
      this.showMorePopup = false
    },
    
    async submitForm() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善所有必填项',
          icon: 'none'
        })
        return
      }
      
      this.isSubmitting = true
      
      try {
        // 构建表单数据
        const formData = {
          feedback_type: this.selectedProblemTypeId,
          content: this.problemDescription.trim(),
          images: this.imageUrls,
        }
        
        const res = await this.$http.post('/h5/user/feedback/submitFeedback', formData)
        uni.showToast({
          title: res.msg,
          icon: 'success'
        })
        
        // 重置表单
        setTimeout(() => {
          this.selectedProblemType = ''
          this.selectedProblemTypeId = ''
          this.problemDescription = ''
          this.uploadedImages = []
          this.isSubmitting = false
          this.imageUrls = [] 
          // 返回上一页
          uni.navigateBack()
        }, 2000)
        
      } catch (error) {
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
        this.isSubmitting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.online-service-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}



.form-container {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 0 30rpx;
}

.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  
  .required {
    color: #ff4757;
    font-size: 28rpx;
    margin-right: 8rpx;
  }
  
  .label-text {
    font-size: 28rpx;
    color: #333;
  }
}

.form-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  
  .placeholder-text {
    color: #999;
    font-size: 28rpx;
  }
  
  .selected-text {
    color: #0B1F20;
    font-size: 28rpx;
  }
  
  .contact-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}

.form-textarea {
  position: relative;
  
  .textarea-input {
    width: calc(100% - 40rpx);
    min-height: 200rpx;
    padding: 20rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    background-color: #fff;
    line-height: 1.5;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .textarea-counter {
    position: absolute;
    bottom: 10rpx;
    right: 20rpx;
    
    .counter-text {
      font-size: 24rpx;
      color: #999;
      
      &.warning {
        color: #ff6b35;
      }
    }
  }
}

.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  
  .uploaded-image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
  }
  
  .delete-btn {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 40rpx;
    height: 40rpx;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  
  .upload-text {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
}

.upload-tip {
  margin-top: 20rpx;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
    line-height: 1.4;
  }
}

.submit-container {
  padding: 40rpx 30rpx;
  background-color: #fff;
  margin-top: 20rpx;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(90deg, #FF3F39 0%, #FF7937 100%);
  border-radius: 8rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  
  &:disabled {
    background-color: #ccc;
  }
}

.more-popup {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
  
  .popup-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-text {
      font-size: 28rpx;
      color: #333;
      margin-left: 20rpx;
    }
  }
  
  .popup-cancel {
    padding: 30rpx 0;
    text-align: center;
    
    .cancel-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.debug-info {
  margin-top: 10rpx;
  padding: 10rpx;
  background-color: #f0f0f0;
  border-radius: 4rpx;
  
  .debug-text {
    font-size: 24rpx;
    color: #666;
    display: block;
    margin-bottom: 5rpx;
  }
}
</style>
